<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-alert
            title="注意：只允许为第三级设置相关参数！"
            type="warning"
            show-icon
            :closable="false"
            class="alertK"
          ></el-alert>

          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectedCatekeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>

          <!-- tab栏切换 -->
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="动态参数" name="many">
              <el-button
                type="primary"
                size="mini"
                :disabled="isBtnDisabled"
                @click="addParamsdialogVisible=true"
              >添加参数</el-button>
              <!-- 动态参数table表格 -->
              <el-table :data="manyTableData">
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <!-- 利用循环显示内容 -->
                    <el-tag
                      v-for="(item,i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>
                    <!-- 文本输入框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <!-- 按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="mini"
                      @click="editCate(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="deleteCate(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态资源" name="only">
              <el-button
                type="primary"
                size="mini"
                :disabled="isBtnDisabled"
                @click="addParamsdialogVisible=true"
              >添加属性</el-button>
              <!-- 静态资源table表格 -->
              <el-table :data="onlyTableData">
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <!-- 利用循环显示内容 -->
                    <el-tag
                      v-for="(item,i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>
                    <!-- 文本输入框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <!-- 按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="mini"
                      @click="editCate(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="deleteCate(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加动态参数和静态资源的对话框 -->
    <el-dialog
      :title="'添加'+textTitle"
      :visible.sync="addParamsdialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加编辑按钮弹出的对话框 -->
    <el-dialog
      :title="'添加'+textTitle"
      :visible.sync="editParamsdialogVisible"
      width="50%"
      @close="closeEditDialog"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>




<script>
export default {
  data() {
    return {
      cateList: [],
      //   级联选择框双向绑定的数组
      selectedCatekeys: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      addParamsdialogVisible: false,
      addForm: {
        attr_name: ""
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      editParamsdialogVisible: false,
      editForm: {
        attr_name: ""
      },
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 商品分类数据列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      //   console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("获取商品分类数据失败");
      }
      //   获取成功直接赋值
      this.cateList = res.data;
      //   console.log(this.cateList);
    },
    // 获取参数的列表数据  级联选择器里面的函数
    handleChange() {
      this.getParamsData();
    },

    // 切换tab栏触发的函数
    handleTabClick() {
      this.getParamsData();
    },
    async getParamsData() {
      //   console.log(this.selectedCatekeys);
      //   如果级联选择框双向绑定的数组  数组长度不为3，则清空该数组
      if (this.selectedCatekeys.length !== 3) {
        this.selectedCatekeys = [];
        // 当级联选择器选中的是二级分类的时候，下面的table表格应该隐藏
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      //   console.log(this.selectedCatekeys);
      //   如果长度为三，则发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      // console.log(res.data);
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];

        // 默认文本框是不可见的
        item.inputVisible = false;
        // 默认文本框的内容为空
        item.inputValue = "";
      });

      if (res.meta.status !== 200) {
        this.$message.error("获取数据失败");
      }
      //   console.log(res.data);
      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 关闭对话框重置内容
    closeDialog() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击确定按钮，添加分类
    addCate() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        //   如果验证通过则发送请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败");
        }
        // 添加成功的话，则有提示信息，刷新数据  关闭对话框
        this.$message.success("添加分类成功");
        this.getParamsData(), (this.addParamsdialogVisible = false);
      });
    },
    // 点击编辑按钮以后
    async editCate(attr_id) {
      // 根据 ID 查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      );
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类参数失败");
      }
      this.editForm = res.data;

      this.editParamsdialogVisible = true;
    },
    // 重置对话框
    closeEditDialog() {
      //   this.$refs.editFormRef.resetFields();
    },
    // 点击确定按钮以后
    editCateSure() {
      // 先进行预验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        //   预验证通过以后，发起请求
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        );
        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("修改数据失败");
        }
        this.$message.success("修改数据成功");
        this.getParamsData(), (this.editParamsdialogVisible = false);
      });
    },
    // 删除分类
    async deleteCate(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      //   console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      //   确定删除，发起请求
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );

      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除分类参数失败");
      }
      //   删除成功，  提示信息   刷新数据
      this.$message.success("删除分类参数成功");
      this.getParamsData();
    },
    // 键盘弹起和失去焦点是触发的事件
    async handleInputConfirm(row) {
      // console.log("ok");
      // 如果没有填内容  隐藏文本框和清除内容
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = "";
        return;
      }
      // 如果没有被return出去，则需要做后续处理
      row.attr_vals.push(row.inputValue.trim());
      row.inputVisible = false;
      row.inputValue = "";

      // 发起请求
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("添加参数失败");
      }
      this.$message.success("添加参数成功");
      // console.log(res);
    },
    // 点击按钮触发的事件
    showInput(row) {
      row.inputVisible = true;
      // 获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleClose(i, row) {
      // ["黄春雨10片-补水滋润,黑春雨10片-轻透补水,白春雨10片-焕白保湿", "11", "22", "33", __ob__: Observer]
      // console.log(row.attr_vals);
      row.attr_vals.splice(i, 1);
      // console.log(row.attr_vals);   此时会少一个
      // 发起请求
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("添加参数失败");
      }
      this.$message.info("删除参数成功");
      // console.log(res);
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCatekeys.length !== 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.selectedCatekeys.length == 3) {
        return this.selectedCatekeys[2];
      }
      return null;
    },
    textTitle() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态资源";
    }
  }
};
</script>


<style lang="less" scoped>
.alertK {
  margin-bottom: 15px;
}
.input-new-tag {
  width: 150px;
}
.el-tag {
  margin-right: 15px;
}
</style>